#include "camera.h"
extern pthread_mutex_t mutex;
extern char* newbuffer;
extern int vedio_real_len;
int port=9000; 
void send_camera(int fd,struct json_object*obj)
{     
      struct json_object*val;
      json_object_object_get_ex(obj,"deviceid",&val); //获取deviceid
      
      const char* id=(const char*)json_object_get_string(val);//保存摄像头号deviceid到id中
      
     
      insert(fd,id);//将deviceid和id绑定放在链表中
       

      //接着服务器向板子客户端发送一个序列告知udp的端口号用于板子创建udp,发视频数据过来
      //发送 {"cmd":"port_info","port":port};  给板子
      struct json_object*se=json_object_new_object();
      json_object_object_add(se,"cmd",json_object_new_string("port_info"));
      json_object_object_add(se,"port",json_object_new_int(port));
      char*buf=(char*)json_object_to_json_string(se);
      port++;//端口号++，用于app客户端连接
      if(send(fd,buf,strlen(buf),0)<0)//通过tcp发送给板子{"cmd":"port_info","port":port};
      {
          printf("send error");
          exit(6);

      }
     int sockfd=socket(AF_INET,SOCK_DGRAM,0);//创建udp服务端，用来接收板子发来的视频数据
      if(sockfd<0)
      {
        printf("server udp error");
        exit(7);


      }
    
      struct sockaddr_in udp_server;
      udp_server.sin_family=AF_INET;
      udp_server.sin_port=htons(port-1);//端口号9000
      udp_server.sin_addr.s_addr=inet_addr(IP);//自己的ip地址
      socklen_t le=sizeof(udp_server);
      if(bind(sockfd,(const struct sockaddr*)&udp_server,le)<0)//绑定
      {
        printf("server udp bidn error");
        exit(8);
      }
     

     char*buffer=(char*)malloc(VEDIOLEN);//动态申请内存保存视频数据 最大验证视频一帧60k VEDIOLEN 100k  ，buffer作为搬运缓冲区
     int recv_size;//用来保存视频的真实大小，可能会丢帧
     struct sockaddr_in camera_client;//板子客户端信息保存在该结构体
     socklen_t len=sizeof(camera_client);
    
     while(1)
     {   memset(buffer,0,VEDIOLEN);//清除接收缓冲区
     
         recv_size=recvfrom(sockfd,buffer,VEDIOLEN,0,(struct sockaddr*)&camera_client,(socklen_t*)&len);//接收视频数据
         printf("recv_size %d\n",recv_size);
        if(recv_size<=0)
        {
            printf("server no recv");
            exit(9);


        }
     
        pthread_mutex_lock(&mutex);        //因为要从板子客户端读取视频数据带服务器缓冲区，缓冲区视频数据要搬运到app
        memcpy(newbuffer,buffer, recv_size);//newbuffer为保存视频数据的缓冲区
        vedio_real_len=recv_size;
        pthread_mutex_unlock(&mutex);      //解锁
       printf("接收到一张图片，大小为 %d\n",recv_size);
     }


}